package com.unlcn.ils.wms.backend.service.sys.impl;

import cn.huiyunche.commons.exception.BusinessException;
import com.unlcn.ils.wms.backend.enums.CarEnableEnum;
import com.unlcn.ils.wms.backend.enums.DeleteFlagEnum;
import com.unlcn.ils.wms.backend.enums.StatusEnum;
import com.unlcn.ils.wms.backend.enums.UserTypeEnum;
import com.unlcn.ils.wms.backend.service.sys.CardService;
import com.unlcn.ils.wms.base.mapper.extmapper.SysUserExtMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsCardExtMapper;
import com.unlcn.ils.wms.base.mapper.sys.SysUserMapper;
import com.unlcn.ils.wms.base.mapper.sys.WmsCardMapper;
import com.unlcn.ils.wms.base.model.sys.SysUser;
import com.unlcn.ils.wms.base.model.sys.SysUserExample;
import com.unlcn.ils.wms.base.model.sys.WmsCard;
import com.unlcn.ils.wms.base.model.sys.WmsCardExample;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by lenovo on 2017/11/2.
 */
@Service
public class CardServiceImpl implements CardService {

    @Autowired
    private WmsCardMapper wmsCardMapper;

    @Autowired
    private WmsCardExtMapper wmsCardExtMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public List<WmsCard> selectCardLine(Map<String, Object> paramsMap) {
        return wmsCardExtMapper.cardLine(paramsMap);
    }

    @Override
    public Integer countCardLineCount(Map<String, Object> paramsMap) {
        return wmsCardExtMapper.cardLineCount(paramsMap);
    }

    /**
     * 新建
     *
     * @param wmsCard
     * @return
     */
    @Override
    public Integer add(WmsCard wmsCard) throws Exception {
        //校验
        checkAddOrUpdate(wmsCard, wmsCard.getId());
        if (StringUtils.isNotBlank(wmsCard.getCreateBy()) && StringUtils.isNumeric(wmsCard.getCreateBy())){
            SysUser sysUser = sysUserMapper.selectByPrimaryKey(Integer.parseInt(wmsCard.getCreateBy()));
            if (sysUser != null){
                wmsCard.setCreateBy(sysUser.getName());
            }
        }
        wmsCard.setStartTime(new Date());
        int normal = DeleteFlagEnum.NORMAL.getValue();
        wmsCard.setIsDelete(normal);
        wmsCard.setGmtCreate(new Date());
        return wmsCardMapper.insert(wmsCard);
    }

    /**
     * 校验
     *
     * @param wmsCard
     * @throws Exception
     */
    private void checkAddOrUpdate(WmsCard wmsCard, Long id) throws Exception {
        if (wmsCard == null) {
            throw new BusinessException("参数为空");
        }
        if (wmsCard.getDriverId() == null) {
            throw new BusinessException("请选择绑定司机");
        }
        if (StringUtils.isBlank(wmsCard.getCardNum())) {
            throw new BusinessException("卡号不能为空");
        }

        boolean carNumCheckResult = queryCheckCarNum(wmsCard.getCardNum(), id);
        if (!carNumCheckResult) {
            throw new BusinessException("该卡号已绑定");
        }
        boolean checkDriverIdResult = queryCheckDriverId(wmsCard.getDriverId(), id);
        if (!checkDriverIdResult) {
            throw new BusinessException("该司机已绑定");
        }

    }

    /**
     * 修改
     * @param wmsCard
     * @return
     * @throws Exception
     */
    @Override
    public Integer modify(WmsCard wmsCard) throws Exception {
        //校验
        if (wmsCard.getId() == null){
            throw new BusinessException("请选择要修改的数据");
        }
        checkAddOrUpdate(wmsCard, wmsCard.getId());

        WmsCard primaryKeyCar = wmsCardMapper.selectByPrimaryKey(wmsCard.getId());
        if (primaryKeyCar == null){
            throw new BusinessException("找不到对应的数据");
        }
        if (wmsCard.getStatus() == CarEnableEnum.DISABLED.getCode()) {
            wmsCard.setEndTime(new Date());
        }
        wmsCard.setGmtUpdate(new Date());
        if (StringUtils.isNotBlank(wmsCard.getUpdateBy()) && StringUtils.isNumeric(wmsCard.getUpdateBy())){
            SysUser sysUser = sysUserMapper.selectByPrimaryKey(Integer.parseInt(wmsCard.getUpdateBy()));
            if (sysUser != null){
                wmsCard.setUpdateBy(sysUser.getName());
            }
        }
        wmsCardMapper.updateByPrimaryKeySelective(wmsCard);
        if (wmsCard.getStatus() == CarEnableEnum.USABLE.getCode()) {

            WmsCard updateCar = wmsCardMapper.selectByPrimaryKey(wmsCard.getId());
            updateCar.setEndTime(null);
            wmsCardMapper.updateByPrimaryKey(updateCar);
        }
        return null;
    }

    /**
     * 门禁卡获取当前可用的司机
     *
     * @return
     */
    @Override
    public List<SysUser> queryDriverUser() {
        //Map<String, Object> paramsMap = new HashMap<String, Object>();
        //paramsMap.put("type", 2);
        SysUserExample example = new SysUserExample();
        example.createCriteria()
                .andIsDeletedEqualTo(DeleteFlagEnum.NORMAL.getValue())
                .andTypeEqualTo(UserTypeEnum.DRIVER.getValue())
                .andEnableEqualTo(StatusEnum.RIGHT.getValue());
        return sysUserMapper.selectByExample(example);
    }

    /**
     * 判断当前卡号是否有可用状态下的绑定
     *
     * @param carNum
     * @return true-未绑定, false-已绑定
     * @throws Exception
     */
    @Override
    public boolean queryCheckCarNum(String carNum, Long id) throws Exception {
        boolean resultBoolean = false;
        if (StringUtils.isNotBlank(carNum)) {
            WmsCardExample wmsCardExample = new WmsCardExample();
            wmsCardExample.setOrderByClause(" id desc ");
            int normal = DeleteFlagEnum.NORMAL.getValue();
            WmsCardExample.Criteria criteria = wmsCardExample.createCriteria();
            criteria.andCardNumEqualTo(carNum);
            criteria.andStatusEqualTo(CarEnableEnum.USABLE.getCode());
            criteria.andIsDeleteEqualTo(normal);
            if (id != null) {
                criteria.andIdNotEqualTo(id);
            }
            int count = wmsCardMapper.countByExample(wmsCardExample);
            if (count <= 0) {
                resultBoolean = true;
            }
        }
        return resultBoolean;
    }

    /**
     * 判断当前司机下的是否有可用的绑定
     *
     * @param driverId
     * @return true-未绑定, false-已绑定
     * @throws Exception
     */
    @Override
    public boolean queryCheckDriverId(Long driverId, Long id) throws Exception {
        boolean resultBoolean = false;
        if (driverId != null) {
            WmsCardExample wmsCardExample = new WmsCardExample();
            wmsCardExample.setOrderByClause(" id desc ");
            int normal = DeleteFlagEnum.NORMAL.getValue();
            WmsCardExample.Criteria criteria = wmsCardExample.createCriteria();
            criteria.andDriverIdEqualTo(driverId);
            criteria.andStatusEqualTo(CarEnableEnum.USABLE.getCode());
            criteria.andIsDeleteEqualTo(normal);
            if (id != null) {
                criteria.andIdNotEqualTo(id);
            }
            int count = wmsCardMapper.countByExample(wmsCardExample);
            if (count <= 0) {
                resultBoolean = true;
            }
        }
        return resultBoolean;
    }
}
